<template>
  <MesBox
    title="报工"
    v-model="visible"
    :width="1000"
    :height="300"
    :onModelClose="onModelClose"
  >
    <MesForm
      :formFields="formFields"
      :formRules="formRules"
      ref="myForm"
    ></MesForm>
    <template #footer>
      <el-button type="success" @click="save('normal')">
        <i class="el-icon-check"></i>
        保存
      </el-button>
      <el-button
        type="danger"
        v-if="formFields.NoGoodQty !== 0"
        @click="save('repair')"
      >
        <i class="el-icon-check"></i>
        不良补报
      </el-button>
    </template>
  </MesBox>
</template>

<script setup>
import MesBox from '@/components/basic/MesBox.vue'
import MesForm from '@/components/basic/MesForm.vue'
import { ref, getCurrentInstance } from 'vue'
// import { getNowDate } from '@/uitils/dateFormatUtil'
import { useStore } from 'vuex'

defineEmits(['parentCall'])
const myForm = ref(null)
let search = null
const store = useStore()
let that = getCurrentInstance().appContext.config.globalProperties
let visible = ref(false)
let Type = ref('')
let formFields = ref({
  WorkOrder_Id: null,
  Process_Id: null,
  Product_Id: null,
  ProductCode: null,
  ProductName: null,
  ProductStandard: null,
  MachineId: null, //从设备中拉出来
  ProductUser: null, //用户ID
  // ReportQty: null, //报工数
  Unit_Id: '',
  GoodQty: 0, //报工都是0
  NoGoodQty: 0, //报工都是0
  ScrapQty: 0,
  ProcessProgress: '', // 实际数/计划数
  StartDate: '', //reporttime
  EndDate: '', //reporttime
  ProcessStatus: '2', //工序状态
  ApproveStatus: '2', //审批状态
  ReportTime: '',
  ApproveUser: '',
  StandardProgress: '',
  UnitPrice: '',
  GuessPrice: 0,
  WoCode: '',
  ProcessName: '',
  ProductUsers: '',
  MoCode: '',
})
let formRules = ref([
  [
    {
      title: '工单Id',
      field: 'WorkOrder_Id',
      hidden: true,
    },
    {
      title: '工单',
      field: 'WoCode',
      disabled: true,
    },
    {
      title: '工序ID',
      field: 'Process_Id',
      hidden: true,
    },
    {
      title: '工序名称',
      field: 'ProcessName',
      disabled: true,
    },
    {
      title: '产品',
      field: 'ProductName',
      disabled: true,
    },
  ],
  [
    {
      title: '产品编号',
      field: 'ProductCode',
      disabled: true,
    },
    {
      title: '规格',
      field: 'ProductStandard',
      disabled: true,
    },
    {
      title: '工序进度',
      field: 'ProcessProgress',
      disabled: true,
    },
  ],
  [
    {
      title: '生产人员',
      field: 'ProductUsers',
      type: 'selectList',
      required: true,
      dataKey: 'user',
      data: [],
    },
    {
      title: '设备名称',
      field: 'MachineId',
      type: 'select',
      dataKey: 'MachineList',
      // required: true,
    },
    {
      title: '报废数',
      field: 'ScrapQty',
      type: 'number',
      required: true,
    },
  ],
  [
    {
      title: '良品数',
      field: 'GoodQty',
      type: 'number',
      required: true,
    },
    {
      title: '不良数',
      field: 'NoGoodQty',
      type: 'number',
      required: true,
    },
    {
      title: '开工时间',
      field: 'ReportTime',
      type: 'datetime',
      required: true,
    },
  ],
])

const open = async (row, searchFun, type) => {
  Type.value = type
  search = searchFun
  visible.value = true
  let {
    Process_Id,
    Product_Id,
    ProductCode,
    ProductName,
    ProductStandard,
    Unit_Id,
    WoCode,
    ProcessName,
    PlanQty,
    WoCodeChild,
    WorkOrderChildren_Id,
  } = row
  // console.log(row)
  formFields.value.Process_Id = Process_Id
  formFields.value.Product_Id = Product_Id
  formFields.value.ProductCode = ProductCode
  formFields.value.ProductName = ProductName
  formFields.value.ProductStandard = ProductStandard
  formFields.value.Unit_Id = Unit_Id
  formFields.value.WoCode = WoCode
  formFields.value.ProcessName = ProcessName
  formFields.value.WorkChildCode = WoCodeChild
  formFields.value.WorkOrder_Id = WorkOrderChildren_Id
  formFields.value.ProcessProgress = await getProgress({
    Process_Id,
    Product_Id,
    PlanQty,
    WorkOrder_Id: WorkOrderChildren_Id,
  })

  //冲压，压合工序必填设备
  if (
    ProcessName.indexOf('冲压') !== -1 ||
    ProcessName.indexOf('压合') !== -1
  ) {
    formRules.value[2][1].required = true
  } else {
    formRules.value[2][1].required = false
  }
}

const getProgress = async (param) => {
  let { WorkOrder_Id, Process_Id, Product_Id, PlanQty } = param
  let res = await that.http.get(
    `api/Production_ReportWorkOrder/getProgress?workOrder_Id=${WorkOrder_Id}&processId=${Process_Id}&productId=${Product_Id}&planQty=${PlanQty}`
  )
  // console.log(res)
  return res.processProgress
}

const save = (reportType) => {
  myForm.value.validate(async (valid) => {
    if (valid) {
      if (reportType == 'normal') {
        formFields.value.ApproveUser = store.state.userInfo.userName
        formFields.value.ProductUser = formFields.value.ProductUsers.join(';')
        // console.log(formFields.value)
        let res = null
        let url = ''
        if (Type.value == '生产工单') {
          url = '/api/Production_ReportWorkOrder/Add'
        } else {
          url = '/api/Production_ReportReWorkOrder/Add'
        }

        res = await that.http.post(
          url,
          {
            mainData: formFields.value,
            detailData: null,
            delKeys: null,
          },
          true
        )
        if (res.status) {
          that.$message.success(res.message)
          clearForm()
          visible.value = false
          search()
        } else {
          if (res.message !== '') {
            that.$message.error(res.message)
          } else {
            that.$message.error('保存失败')
          }
        }
      } else {
        let res = await that.http.post(
          '/api/Production_ReportWorkOrder/CreateWorkReport',
          formFields.value,
          true
        )
        if (res.status) {
          that.$message.success(res.message)
          clearForm()
          visible.value = false
          search()
        } else {
          that.$message.error(res.message)
        }
      }
    }
  })
}

const clearForm = () => {
  formFields.value.GoodQty = 0
  formFields.value.NoGoodQty = 0
  formFields.value.ScrapQty = 0
  formFields.value.ProductUsers = ''
  formFields.value.ProductUser = ''
  formFields.value.MachineId = ''
  formFields.value.ReportTime = ''
}

const onModelClose = () => {
  visible.value = false
  clearForm()
}

defineExpose({ open })
</script>

<style lang="less" scoped></style>
